#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

from pymongo import MongoClient
import MySQLdb

# MongoDB Info
DB_NAME = "mesh"
COLLECTION_NAME = "descriptor"
connection = MongoClient('localhost', 27017)
db = connection[DB_NAME]
collection = db[COLLECTION_NAME]

# MySQL Info
DATABASE_NAME = 'pmc_meta'
HOST = '10.10.31.22'
PORT = '3306'
USER_NAME = 'pmc'
PASSWORD = 'pmc'
CHAR_SET = 'utf8'
conn = MySQLdb.connect(host=HOST, user=USER_NAME, passwd=PASSWORD, db=DATABASE_NAME, charset=CHAR_SET)

results = collection.find({"tree": {"$exists": 1}})
for result in results:
    id = result["id"]
    name = result["name"]
    trees = result["tree"]
    for tree in trees:
        tree_root = tree.split(".")[0]
        # print id+"\t"+name+"\t"+tree_root+"\t"+tree
        cursor = conn.cursor()
        sql = "insert into tb_dds_mesh_descriptor_tree values(0,%s,%s,%s,%s)"
        params = (id, name, tree_root, tree)
        result = cursor.execute(sql, params)
        conn.commit()
        cursor.close()
conn.close()
connection.close()
